package com.ls.springbootdemo.common.response;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ls.springbootdemo.common.enums.ResponseCode;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author 挥之以墨
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MyResponse<T> implements Serializable {

    private int code;
    private String msg;
    private T data;

    /**
     * 请求成功响应
     */
    public static <T> MyResponse<T> buildSuccess(T data) {
        return MyResponse.<T>builder()
                .code(ResponseCode.SUCCESS.getCode())
                .msg(ResponseCode.SUCCESS.getMsg())
                .data(data)
                .build();
    }

    /**
     * 默认成功响应
     */
    public static <T> MyResponse<T> buildDefaultSuccess() {
        return buildSuccess(null);
    }

    /**
     * 默认失败响应
     */
    public static <T> MyResponse<T> buildDefaultFailure() {
        return buildFailure(ResponseCode.COMMON_ERROR.getMsg());
    }

    /**
     * 自定义返回值的响应
     *
     * @param msg 错误提示消息
     */
    public static <T> MyResponse<T> buildFailure(String msg) {
        return MyResponse.<T>builder()
                .code(ResponseCode.COMMON_ERROR.getCode())
                .msg(msg)
                .build();
    }

    @JsonIgnore
    public boolean isSuccess() {
        return this.code == ResponseCode.SUCCESS.getCode();
    }

}
